<template>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" />
        <Editor style="height: 500px; overflow-y: hidden;" @onChange="onChange" @onCreated="handleCreated" />
    </div>
</template>
<script setup lang="ts">
import { ref, onMounted, shallowRef, watch } from 'vue'

import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
//引入api接口
import { uploadApi } from '@/api';

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
//const valueHtml = ref('<p>hello</p>')

onMounted(() => {
    console.log(props.modelValue);

})

let props = defineProps({
    modelValue: {
        type: String,
        default: ""
    }
})
let emit = defineEmits(['update:modelValue'])


const onChange = (editor: any) => {
    console.log("触发了编辑器");
    console.log("内容获取：", editor.children);
    emit('update:modelValue', editor.getHtml())
}
const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！

    editor.getConfig().MENU_CONF['uploadImage'] = {
        // 自定义上传
        async customUpload(file: File, insertFn: any) {  // TS 语法
            let reader = new FileReader()
            // file 即选中的文件
            reader.readAsDataURL(file)
            //先加载获取的内容 及 呼叫api接口
            reader.onload = () => {
                console.log(reader.result);
                console.log(file.name);
                uploadApi.upload.call({
                    name: file.name,
                    base64: reader.result
                }).then((res: any) => {
                    //console.log(res);
                    // 自己实现上传，并得到图片 url alt href
                    // 最后插入图片
                    insertFn(res, '', "")
                })

            }
        }
    }




    // editor.setHtml(props.modelValue)
    // console.log("赋值之后的变化")
}

watch(() => props.modelValue, (newVal: any, oldVal: any) => {
    console.log("发生了变化，我已经感应到了");
    console.log(oldVal);

    editorRef.value.setHtml(newVal)
})

</script>